import { baseUrl } from '@/config'
const currentApis = []

const history = {
  push: (url) => {
    wx.navigateTo({
      url
    })
  },
  back: (delta = 1) => {
    wx.navigateBack({
      delta
    })
  },
  goBack: () => {
    history.back()
  },
  replace: (url) => {
    wx.redirectTo({
      url
    })
  }
}

const message = {
  info: (param, type) => {
    let msg,
      duration = 2000,
      onClose

    if (Object.prototype.toString.call(param) === '[object Object]') {
      msg = param.msg
      param.duration && (duration = param.duration)
      onClose = param.onClose
    } else {
      msg = param
    }

    onClose && setTimeout(() => onClose(), duration)
    return wx.showToast({ title: msg, icon: 'none', duration })
  },
  loading: (msg) => wx.showLoading({ title: msg }),
  success: (msg) => message.info(msg, 'success'),
  error: (msg) => message.info(msg, 'error')
}

const logout = (url) => {
  // request('DELETE', {
  //   api: '/auth/token/logout',
  //   success: ({data}) => {
  //   }
  // })
  wx.setStorageSync('userInfo', '')
  wx.reLaunch({
    url: '/pages/login/index'
  })
}

const request = (method, options = {}) => {
  const userInfo = wx.getStorageSync('userInfo') || {}
  let token = userInfo.access_token
  const {
    api,
    data,
    success,
    fail,
    noLoading = false,
    noTip = false,
    loadingText,
    serialize,
    headers
  } = options

  const url = api.includes('http') ? api : baseUrl + api

  if (!url) {
    return wx.showToast({
      title: '必须包含请求URL'
    })
  }

  !noLoading &&
    wx.showLoading({
      title: loadingText || 'loading'
    })

  let contentType = 'application/json'
  if (serialize) contentType = 'application/x-www-form-urlencoded'

  let header = {
    Authorization: '',
    'content-type': contentType
  }

  if (!token) {
    header.Authorization = 'Basic YWd0OmFndA=='
    header.isToken = 'false'
  } else {
    header.Authorization = `Bearer ${token}`
  }

  header = { ...header, ...headers }

  return new Promise((resolve, reject) => {
    if (currentApis.includes(url)) {
      reject(new Error('接口正在请求中...'))
      fail(new Error('接口正在请求中...'))
      return
    } else {
      currentApis.push(url)
    }

    wx.request({
      url, // 仅为示例，并非真实的接口地址
      data: data,
      method,
      header,
      timeout: 60000,
      success: (res) => {
        currentApis.splice(currentApis.indexOf(url), 1)
        !noLoading && wx.hideLoading()
        wx.stopPullDownRefresh()

        const { data, code, msg, access_token } = res.data

        if (res.statusCode === 424 || res.statusCode === 426) logout()
        if (code === '1004') logout()

        if (([200, 0].includes(code) && data !== false) || access_token) {
        // if ([200, 0].includes(code) || access_token) {
          success && success(access_token ? res.data : res.data)
          resolve(res.data)
        } else {
          !noTip &&
            wx.showToast({
              title: msg || '网络错误，请稍后重试',
              icon: 'none',
              duration: 3000
            })
          fail && fail(res.data)
          reject(res.data)
        }
      },
      fail(error) {
        currentApis.splice(currentApis.indexOf(url), 1)
        wx.stopPullDownRefresh()
        wx.hideLoading()
        !noTip &&
          wx.showToast({
            title: error.message || '网络错误，请稍后重试',
            icon: 'none',
            duration: 3000
          })
        reject(error)
      },
      complete() {
        // wx.hideLoading()
      }
    })
  })
}

const get = request.bind(null, 'GET')
const post = request.bind(null, 'POST')

const ocr = (imgUrl, ocr_type = 1) => {
  return wx.serviceMarket
    .invokeService({
      service: 'wx79ac3de8be320b71', // '固定为服务商OCR的appid，非小程序appid',
      api: 'OcrAllInOne',
      data: {
        img_url: imgUrl,
        data_type: 3,
        ocr_type
      }
    })
    .then((res) => {
      console.log('invokeService success', res)
      return res
    })
    .catch((err) => {
      console.error('invokeService fail', err)
    })
}

export { history, post, get, message, logout, ocr }
